package com.leps.nq.sys.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.leps.nq.common.aspect.Log;
import com.leps.nq.common.enums.BusinessType;
import com.leps.nq.common.vo.R;
import com.leps.nq.common.vo.RBuilder;
import com.leps.nq.sys.entity.SysDictData;
import com.leps.nq.sys.service.ISysDictDataService;
import com.leps.nq.sys.vo.DictDataVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 字典数据表 前端控制器
 * </p>
 *
 * @author hex
 * @since 2022-05-20
 */
@RestController
@RequestMapping("/sys/sys-dict-data")
@Api(tags = "数据字典查询接口")
public class SysDictDataController {
    @Autowired
    ISysDictDataService dictDataService;

    @GetMapping
    @ApiOperation("根据字典类型查询字典列表，如果不传参数则查询所有的字典数据")
    public R<List<DictDataVo>> getDictData(String dictType) {
        List<SysDictData> list = this.dictDataService.lambdaQuery().eq(StrUtil.isNotBlank(dictType), SysDictData::getDictType, dictType)
                .orderByAsc(SysDictData::getDictType)
                .orderByAsc(SysDictData::getDictSort)
                .list();
        List<DictDataVo> volist = new ArrayList<>();
        if(ObjectUtil.isNotEmpty(list)) {
            volist = list.stream().map(item -> BeanUtil.toBean(item, DictDataVo.class)).collect(Collectors.toList());
        }
        return RBuilder.ok(volist);
    }

    @PostMapping
    @ApiOperation("添加字典数据")
    @Log(title = "数据字典", businessType = BusinessType.INSERT)
    public R create(@RequestBody SysDictData dictData) {
        boolean save = this.dictDataService.save(dictData);
        return RBuilder.ofBoolean(save);
    }

    @PutMapping
    @ApiOperation("修改字典数据")
    @Log(title = "数据字典", businessType = BusinessType.UPDATE)
    public R update(@RequestBody SysDictData entity) {
        boolean updated = this.dictDataService.updateById(entity);
        return RBuilder.ofBoolean(updated);
    }

    @DeleteMapping
    @ApiModelProperty("删除字典数据")
    @Log(title = "数据字典", businessType = BusinessType.DELETE)
    public R remove(@RequestBody List<Long> id) {
        boolean deleted = this.dictDataService.removeBatchByIds(id);
        return RBuilder.ofBoolean(deleted);
    }
}
